// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.StockOutFinishedProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.DbOrganizationMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.StockOutFinishedProductMapper;
import com.fowo.api.mapper.StockOutProductMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.db.organization.DbOrganizationItemVo;
import com.fowo.api.model.db.organization.DbOrganizationSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductAnnulAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductConfirmationOfDeliveryAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductConfirmationOfDeliverysAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductCreateReceivableAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductExcelPo;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductImportPo;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductImportTheWarehouseReceiptAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductItemVo;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductPrintOutStockSheetTemplateAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductPrintOutStockSheetTemplatesAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductPrintOutTheStockListAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductPrintOutTheStockListsAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductPushStockInAndStockOutAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductPushStockOutAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductReferAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductSearchParamPo;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductSubmitAndReleaseAction;
import com.fowo.api.model.stock.out.finished.product.StockOutFinishedProductVo;
import com.fowo.api.model.stock.out.finished.product.constant.StockOutFinishedProductAStatusEnums;
import com.fowo.api.model.stock.out.finished.product.constant.StockOutFinishedProductDocumentStatusEnums;
import com.fowo.api.model.stock.out.finished.product.constant.StockOutFinishedProductProductTypeEnums;
import com.fowo.api.model.stock.out.product.StockOutProductItemVo;
import com.fowo.api.model.stock.out.product.StockOutProductItemVoPages;
import com.fowo.api.model.stock.out.product.StockOutProductSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.StockOutFinishedProductService;
import com.fowo.api.service.StockOutProductService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysDepartmentMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDepartmentSearchParamPo;
import com.fowo.api.sys.model.SysDepartmentVo;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 成品出库单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，郑天琪
 */
@Slf4j
@DataObjectType(StockOutFinishedProduct.class)
@DS("ds24")
public class StockOutFinishedProductBaseServiceImpl
  extends ServiceImpl<StockOutFinishedProductMapper, StockOutFinishedProduct>
  implements StockOutFinishedProductService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseName", "w.`name`");
      put("toWarehouseName", "w2.`name`");
      put("deptName", "sd.`name`");
      put("customerShopName", "si.`shop_name`");
      put("needOrgName", "do.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected StockOutFinishedProductService self;

  @Resource
  protected StockOutProductService stockOutProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected SysDepartmentMapper sysDepartmentMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected DbOrganizationMapper dbOrganizationMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected StockOutFinishedProductConfirmationOfDeliverysAction stockOutFinishedProductConfirmationOfDeliverysAction;

  @Autowired(required = false)
  protected StockOutFinishedProductPrintOutTheStockListsAction stockOutFinishedProductPrintOutTheStockListsAction;

  @Autowired(required = false)
  protected StockOutFinishedProductAnnulAction stockOutFinishedProductAnnulAction;

  @Autowired(required = false)
  protected StockOutFinishedProductPrintOutStockSheetTemplatesAction stockOutFinishedProductPrintOutStockSheetTemplatesAction;

  @Autowired(required = false)
  protected StockOutFinishedProductReferAction stockOutFinishedProductReferAction;

  @Autowired(required = false)
  protected StockOutFinishedProductConfirmationOfDeliveryAction stockOutFinishedProductConfirmationOfDeliveryAction;

  @Autowired(required = false)
  protected StockOutFinishedProductSubmitAndReleaseAction stockOutFinishedProductSubmitAndReleaseAction;

  @Autowired(required = false)
  protected StockOutFinishedProductImportTheWarehouseReceiptAction stockOutFinishedProductImportTheWarehouseReceiptAction;

  @Autowired(required = false)
  protected StockOutFinishedProductPrintOutStockSheetTemplateAction stockOutFinishedProductPrintOutStockSheetTemplateAction;

  @Autowired(required = false)
  protected StockOutFinishedProductPrintOutTheStockListAction stockOutFinishedProductPrintOutTheStockListAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected StockOutFinishedProductPushStockOutAction stockOutFinishedProductPushStockOutAction;

  @Autowired(required = false)
  protected StockOutFinishedProductPushStockInAndStockOutAction stockOutFinishedProductPushStockInAndStockOutAction;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected StockOutFinishedProductCreateReceivableAction stockOutFinishedProductCreateReceivableAction;

  @Resource
  protected Validator validator;

  /**
   * 创建成品出库单
   * @param model 成品出库单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(StockOutFinishedProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockOutFinishedProduct entity = new StockOutFinishedProduct();
    BeanUtils.copyProperties(model, entity);
    // 设置常量字段
    entity.setProductType("1");
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("CS01");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "StockOutFinishedProduct.orderSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("成品出库单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 成品出库单
   */
  protected void updateAllChilds(StockOutFinishedProductVo model)
    throws Exception {
    if (model.getStockOutProducts() != null) {
      stockOutProductService.saveAllByStockOutId(
        model.getId(),
        model.getStockOutProducts()
      );
    }
  }

  /**
   * 更新成品出库单
   * @param model 成品出库单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(StockOutFinishedProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockOutFinishedProduct entity = this.getById(model.getId());
    if (entity == null || !Objects.equals(entity.getProductType(), "1")) {
      throw new Exception("成品出库单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "orderSn",
      "parentId",
      "totalAmount",
      "totalNum",
      "status",
      "createTime",
      "lastUpdateUser",
      "lastUpdateTime",
      "id",
      "createUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新成品出库单（带空值）
   * @param model 成品出库单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(StockOutFinishedProductVo model)
    throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockOutFinishedProduct entity = this.getById(model.getId());
    if (entity == null || !Objects.equals(entity.getProductType(), "1")) {
      throw new Exception("成品出库单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(StockOutFinishedProduct::getWarehouse, model.getWarehouse())
      .set(StockOutFinishedProduct::getType, model.getType())
      .set(StockOutFinishedProduct::getOutTime, model.getOutTime())
      .set(
        StockOutFinishedProduct::getDocumentStatus,
        model.getDocumentStatus()
      )
      .set(StockOutFinishedProduct::getDept, model.getDept())
      .set(StockOutFinishedProduct::getProductType, model.getProductType())
      .set(StockOutFinishedProduct::getRemark, model.getRemark())
      .set(StockOutFinishedProduct::getAStatus, model.getAStatus())
      .set(StockOutFinishedProduct::getRId, model.getRId())
      .set(
        StockOutFinishedProduct::getLastUpdateUser,
        model.getLastUpdateUser()
      )
      .set(
        StockOutFinishedProduct::getLastUpdateTime,
        model.getLastUpdateTime()
      )
      .set(StockOutFinishedProduct::getNeedOrg, model.getNeedOrg())
      .eq(StockOutFinishedProduct::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    StockOutFinishedProductSearchParamPo search
  ) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 出库单子表(stockOutProducts) 对应的对象
    StockOutProductSearchParamPo stockOutProductsSearchParam =
      new StockOutProductSearchParamPo();
    stockOutProductsSearchParam.setDisableDataPremissions(true);
    stockOutProductsSearchParam.setStockOutIdInList(ids);
    StockOutProductMapper localStockOutProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(StockOutProductMapper.class);
    stockOutProductsSearchParam.applySqlSegments();
    List<Long> stockOutProductsIdList = localStockOutProductMapper.searchIds(
      stockOutProductsSearchParam
    );
    if (!stockOutProductsIdList.isEmpty()) {
      StockOutProductService localStockOutProductService = ContextHolder
        .getApplicationContext()
        .getBean(StockOutProductService.class);
      localStockOutProductService.batchDelete(stockOutProductsIdList);
    }
  }

  /**
   * 删除成品出库单
   * @param id 成品出库单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除成品出库单
   * @param ids 成品出库单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<StockOutFinishedProductImportPo> excelToImportRow(
    StockOutFinishedProductImportPo row,
    Integer rowNumber,
    StockOutFinishedProductVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<StockOutFinishedProductImportPo> ir =
      new ImportRow<StockOutFinishedProductImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<StockOutFinishedProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new StockOutFinishedProductVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, StockOutFinishedProductImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00022")
        );
      StockOutFinishedProductVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setOutTime(SheetUtils.tryToDateTime(row.getOutTime()));
    if (StringUtils.hasText(row.getDocumentStatus())) {
      vo.setDocumentStatus(
        StockOutFinishedProductDocumentStatusEnums.toValue(
          row.getDocumentStatus()
        )
      );
      if (vo.getDocumentStatus() == null) {
        ir.addError(
          "documentStatus",
          "单据状态只能是：“待提交”, “待出库”, “已完成”, “已撤销”"
        );
      }
    }
    if (StringUtils.hasText(row.getProductType())) {
      vo.setProductType(
        StockOutFinishedProductProductTypeEnums.toValue(row.getProductType())
      );
      if (vo.getProductType() == null) {
        ir.addError("productType", "产品类型只能是：“原材料”, “成品”");
      }
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00023")
        );
      StockOutFinishedProductVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getAddType())) {
      List<SysDictAllItem> addTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "addType",
          n -> sysDictService.getDictItems("SCM00035")
        );
      StockOutFinishedProductVo finalVo = vo;
      addTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getAddType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setAddType(i.getItemValue()),
          () ->
            ir.addError(
              "addType",
              String.format(
                "必须为 %s 中之一",
                addTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getAStatus())) {
      vo.setAStatus(
        StockOutFinishedProductAStatusEnums.toValue(row.getAStatus())
      );
      if (vo.getAStatus() == null) {
        ir.addError(
          "aStatus",
          "审批状态只能是：“待提交”, “待出库”, “已完成”, “已撤销”, “待审批”, “已驳回”"
        );
      }
    }
    vo.setRId(SheetUtils.tryToLong(row.getRId()));
    // 处理关联字段“出库仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouse())
    ) {
      WarehouseSearchParamPo warehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseSearchParam.setNameEq(SheetUtils.trim(row.getWarehouseName()));
      warehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseMatches = warehouseMapper.search(
        warehouseSearchParam
      );
      if (warehouseMatches.size() == 0) {
        ir.addError("warehouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (warehouseMatches.size() > 1) {
        ir.addError(
          "warehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouse(warehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“目标仓库”
    if (
      !SheetUtils.isBlank(row.getToWarehouseName()) &&
      SheetUtils.isBlank(row.getToWarehouse())
    ) {
      WarehouseSearchParamPo toWarehouseSearchParam =
        new WarehouseSearchParamPo();
      toWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      toWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getToWarehouseName())
      );
      toWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> toWarehouseMatches = warehouseMapper.search(
        toWarehouseSearchParam
      );
      if (toWarehouseMatches.size() == 0) {
        ir.addError("toWarehouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (toWarehouseMatches.size() > 1) {
        ir.addError(
          "toWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setToWarehouse(toWarehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“组织”
    if (
      !SheetUtils.isBlank(row.getDeptName()) &&
      SheetUtils.isBlank(row.getDept())
    ) {
      SysDepartmentSearchParamPo deptSearchParam =
        new SysDepartmentSearchParamPo();
      deptSearchParam.setLimit(2); // 最大只返回二行记录
      deptSearchParam.setNameEq(SheetUtils.trim(row.getDeptName()));
      deptSearchParam.applySqlSegments();
      List<SysDepartmentVo> deptMatches = sysDepartmentMapper.search(
        deptSearchParam
      );
      if (deptMatches.size() == 0) {
        ir.addError("deptName", "未能在部门中找到匹配的数据");
      } else if (deptMatches.size() > 1) {
        ir.addError("deptName", "关联不唯一，在部门中找到多个匹配的数据");
      } else {
        vo.setDept(deptMatches.get(0).getId());
      }
    }
    // 处理关联字段“客户”
    if (
      !SheetUtils.isBlank(row.getCustomerShopName()) &&
      SheetUtils.isBlank(row.getCustomer())
    ) {
      ShopInfoSearchParamPo customerSearchParam = new ShopInfoSearchParamPo();
      customerSearchParam.setLimit(2); // 最大只返回二行记录
      customerSearchParam.setShopNameEq(
        SheetUtils.trim(row.getCustomerShopName())
      );
      customerSearchParam.applySqlSegments();
      List<ShopInfoItemVo> customerMatches = shopInfoMapper.search(
        customerSearchParam
      );
      if (customerMatches.size() == 0) {
        ir.addError("customerShopName", "未能在店铺中找到匹配的数据");
      } else if (customerMatches.size() > 1) {
        ir.addError(
          "customerShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setCustomer(customerMatches.get(0).getId());
      }
    }
    // 处理关联字段“结算组织”
    if (
      !SheetUtils.isBlank(row.getNeedOrgName()) &&
      SheetUtils.isBlank(row.getNeedOrg())
    ) {
      DbOrganizationSearchParamPo needOrgSearchParam =
        new DbOrganizationSearchParamPo();
      needOrgSearchParam.setLimit(2); // 最大只返回二行记录
      needOrgSearchParam.setNameEq(SheetUtils.trim(row.getNeedOrgName()));
      needOrgSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> needOrgMatches = dbOrganizationMapper.search(
        needOrgSearchParam
      );
      if (needOrgMatches.size() == 0) {
        ir.addError("needOrgName", "未能在组织中找到匹配的数据");
      } else if (needOrgMatches.size() > 1) {
        ir.addError("needOrgName", "关联不唯一，在组织中找到多个匹配的数据");
      } else {
        vo.setNeedOrg(needOrgMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<StockOutFinishedProductImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<StockOutFinishedProductImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            StockOutFinishedProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              StockOutFinishedProductImportPo row,
              AnalysisContext cxt
            ) {
              StockOutFinishedProductVo vo = new StockOutFinishedProductVo();
              ImportRow<StockOutFinishedProductImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<StockOutFinishedProductImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<StockOutFinishedProductImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      StockOutFinishedProductVo vo = new StockOutFinishedProductVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"出库单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "orderSn".equals(m.getField())
          )
      ) {
        vo.setOrderSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "StockOutFinishedProduct.orderSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    StockOutFinishedProductSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "warehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((StockOutFinishedProductItemVo) r).getWarehouseName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00022")
      );
      exportOptions.addFieldMappingOption(
        "documentStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            StockOutFinishedProductDocumentStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "dept",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutFinishedProductItemVo) r).getDeptName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            StockOutFinishedProductProductTypeEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00023")
      );
      exportOptions.addFieldMappingOption(
        "aStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            StockOutFinishedProductAStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "needOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutFinishedProductItemVo) r).getNeedOrgName())
          )
      );
      exportOptions.addStringFields(
        "orderSn",
        "warehouseName",
        "type",
        "documentStatus",
        "parentId",
        "totalAmount",
        "totalNum",
        "deptName",
        "productType",
        "status",
        "remark",
        "aStatus",
        "needOrgName"
      );

      String fileName = String.format(
        "成品出库单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00022");
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00023");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<StockOutFinishedProductExcelPo> items =
      new ArrayList<StockOutFinishedProductExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<StockOutFinishedProductItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<StockOutFinishedProductItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (StockOutFinishedProductItemVo item : list) {
        StockOutFinishedProductExcelPo excel =
          new StockOutFinishedProductExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }
        excel.setDocumentStatus(
          StockOutFinishedProductDocumentStatusEnums.toLabel(
            item.getDocumentStatus()
          )
        );
        excel.setProductType(
          StockOutFinishedProductProductTypeEnums.toLabel(item.getProductType())
        );
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        excel.setAStatus(
          StockOutFinishedProductAStatusEnums.toLabel(item.getAStatus())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "成品出库单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(StockOutFinishedProductExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过源表ID查询成品出库单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByParentId(String parentId) {
    return this.baseMapper.getIdByParentId(parentId);
  }

  /**
   * 通过源表ID查询成品出库单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByParentId(List<String> list) {
    return this.baseMapper.getIdsByParentId(list);
  }

  /**
   * 通过成品出库单主键查询源表ID
   */
  @Override
  public String getParentIdById(Long id) {
    return this.baseMapper.getParentIdById(id);
  }

  /**
   * 通过成品出库单主键查询源表ID列表
   */
  @Override
  public List<String> getParentIdByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getParentIdByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("parentId"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 成品出库单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public StockOutFinishedProductVo getVoById(Long id) throws Exception {
    StockOutFinishedProductVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    StockOutProductSearchParamPo stockOutProductsSearchParamPo =
      new StockOutProductSearchParamPo();
    stockOutProductsSearchParamPo.setStockOutId(id);
    stockOutProductsSearchParamPo.getExtendData().put("queryMode", "sub");
    stockOutProductsSearchParamPo
      .getExtendData()
      .put("queryParent", "StockOutFinishedProduct");
    stockOutProductsSearchParamPo.applySqlSegments();
    vo.setStockOutProducts(
      stockOutProductService.search(stockOutProductsSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询成品出库单
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<StockOutFinishedProductItemVo> pageSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    Page<StockOutFinishedProductItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(StockOutFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(
    Page<StockOutFinishedProductItemVo> pageResult
  ) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<StockOutFinishedProductItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    StockOutProductSearchParamPo stockOutProductsSearchParamPo =
      new StockOutProductSearchParamPo();
    stockOutProductsSearchParamPo.setSort(sort);
    stockOutProductsSearchParamPo.setPageSize(200);
    stockOutProductsSearchParamPo.setStockOutIdInList(
      pageResult
        .getRecords()
        .stream()
        .map(StockOutFinishedProductItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<StockOutProductItemVoPages>> stockOutProductsMaps =
      stockOutProductService.pagesByStockOutId(stockOutProductsSearchParamPo);

    for (StockOutFinishedProductItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "stockOutProducts",
        stockOutProductsMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    StockOutFinishedProductSearchParamPo search
  ) {
    StockOutFinishedProductSearchParamPo parentSearchParam =
      new StockOutFinishedProductSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<StockOutFinishedProductItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      StockOutFinishedProductItemVo itemVo = parentList.get(0);

      StockOutProductSearchParamPo stockOutProductsSearchParamPo =
        new StockOutProductSearchParamPo();
      stockOutProductsSearchParamPo.setPageSize(search.getPageSize());
      stockOutProductsSearchParamPo.setCurrent(search.getCurrent());
      stockOutProductsSearchParamPo.setStockOutId(itemVo.getId());
      return stockOutProductService.pageSearch(stockOutProductsSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 成品出库单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'StockOutFinishedProductOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<StockOutFinishedProductItemVo>> searchOptions(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询成品出库单
   * @param search 查询条件
   * @return 成品出库单列表查询结果
   */
  @Override
  public List<StockOutFinishedProductItemVo> search(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询成品出库单最后更新时间
   * @param search 查询条件
   * @return 成品出库单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(
    StockOutFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 返回满足搜索条件的统计信息
   * @param search 搜索参数
   */
  @Override
  public Map<String, Object> searchForStatistical(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchForStatistical(search);
  }

  /**
   * 确认出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认出库操作"
  )
  @Override
  public void confirmationOfDeliverys(Long id) throws Exception {
    if (stockOutFinishedProductConfirmationOfDeliverysAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductConfirmationOfDeliverysAction.run(id);
  }

  /**
   * 打印出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印出库单操作"
  )
  @Override
  public void printOutTheStockLists(Long id) throws Exception {
    if (stockOutFinishedProductPrintOutTheStockListsAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductPrintOutTheStockListsAction.run(id);
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Override
  public void annul(Long id) throws Exception {
    if (stockOutFinishedProductAnnulAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductAnnulAction.run(id);
  }

  /**
   * 打印出库单（模版）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印出库单（模版）操作"
  )
  @Override
  public void printOutStockSheetTemplates(Long id) throws Exception {
    if (stockOutFinishedProductPrintOutStockSheetTemplatesAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductPrintOutStockSheetTemplatesAction.run(id);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void refer(List<Long> ids) throws Exception {
    if (stockOutFinishedProductReferAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductReferAction.run(ids);
  }

  /**
   * 确认出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认出库操作"
  )
  @Override
  public void confirmationOfDelivery(List<Long> ids) throws Exception {
    if (stockOutFinishedProductConfirmationOfDeliveryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductConfirmationOfDeliveryAction.run(ids);
  }

  /**
   * 提交并出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交并出库操作"
  )
  @Override
  public void submitAndRelease(List<Long> ids) throws Exception {
    if (stockOutFinishedProductSubmitAndReleaseAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductSubmitAndReleaseAction.run(ids);
  }

  /**
   * 导入出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了导入出库单操作"
  )
  @Override
  public void importTheWarehouseReceipt(List<Long> ids) throws Exception {
    if (stockOutFinishedProductImportTheWarehouseReceiptAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductImportTheWarehouseReceiptAction.run(ids);
  }

  /**
   * 打印出库单（模版）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印出库单（模版）操作"
  )
  @Override
  public void printOutStockSheetTemplate(List<Long> ids) throws Exception {
    if (stockOutFinishedProductPrintOutStockSheetTemplateAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductPrintOutStockSheetTemplateAction.run(ids);
  }

  /**
   * 打印出库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印出库单操作"
  )
  @Override
  public void printOutTheStockList(List<Long> ids) throws Exception {
    if (stockOutFinishedProductPrintOutTheStockListAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductPrintOutTheStockListAction.run(ids);
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void custSubmit(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockOutFinishedProduct_custSubmit.js",
      id,
      null,
      this
    );
  }

  /**
   * 下推其他入库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推其他入库单操作"
  )
  @Override
  public void pushStockOut(Long id) throws Exception {
    if (stockOutFinishedProductPushStockOutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductPushStockOutAction.run(id);
  }

  /**
   * 下推生成入库单和出库单(工厂)
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推生成入库单和出库单(工厂)操作"
  )
  @Override
  public void pushStockInAndStockOut(Long id) throws Exception {
    if (stockOutFinishedProductPushStockInAndStockOutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductPushStockInAndStockOutAction.run(id);
  }

  /**
   * 审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了审核操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void outStockApply(Long id) throws Exception {
    StockOutFinishedProductVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareOutStockApply(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOutFinishedProduct updateStatusEntity = new StockOutFinishedProduct();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS02");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 审核 的参数
   */
  protected InventoryOutboundFormVo prepareOutStockApply(
    StockOutFinishedProductVo vo
  ) throws Exception {
    if (!"CS01".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutFinishedProductVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getQuantity())
      );
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 生成应收单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了生成应收单操作"
  )
  @Override
  public void createReceivable(Long id) throws Exception {
    if (stockOutFinishedProductCreateReceivableAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutFinishedProductCreateReceivableAction.run(id);
  }

  /**
   * 取消审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消审核操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelOutbound(Long id) throws Exception {
    StockOutFinishedProductVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareCancelOutbound(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOutFinishedProduct updateStatusEntity = new StockOutFinishedProduct();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS01");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消审核 的参数
   */
  protected InventoryOutboundFormVo prepareCancelOutbound(
    StockOutFinishedProductVo vo
  ) throws Exception {
    if (!"CS02".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutFinishedProductVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getQuantity())
      );
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 全部
   */
  @Override
  public List<StockOutFinishedProductItemVo> all1(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.all1(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<StockOutFinishedProductItemVo> all1Page(
    StockOutFinishedProductSearchParamPo search
  ) {
    Page<StockOutFinishedProductItemVo> all1Page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return all1Page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return all1Page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    all1Page =
      this.baseMapper.all1Page(
          search.toPage(this.baseMapper.all1Count(search)),
          search
        );
    List<Long> recordIds = all1Page
      .getRecords()
      .stream()
      .map(StockOutFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return all1Page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return all1Page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    all1Page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return all1Page;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<?> all1PageWithChildSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      all1Page(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date all1LastUpdateTime(StockOutFinishedProductSearchParamPo search) {
    return this.baseMapper.all1LastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<StockOutFinishedProductItemVo> changesToBeCommitted(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.changesToBeCommitted(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<StockOutFinishedProductItemVo> changesToBeCommittedPage(
    StockOutFinishedProductSearchParamPo search
  ) {
    Page<StockOutFinishedProductItemVo> changesToBeCommittedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return changesToBeCommittedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return changesToBeCommittedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    changesToBeCommittedPage =
      this.baseMapper.changesToBeCommittedPage(
          search.toPage(this.baseMapper.changesToBeCommittedCount(search)),
          search
        );
    List<Long> recordIds = changesToBeCommittedPage
      .getRecords()
      .stream()
      .map(StockOutFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return changesToBeCommittedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return changesToBeCommittedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    changesToBeCommittedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return changesToBeCommittedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<?> changesToBeCommittedPageWithChildSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      changesToBeCommittedPage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date changesToBeCommittedLastUpdateTime(
    StockOutFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.changesToBeCommittedLastUpdateTime(search);
  }

  /**
   * 待出库
   */
  @Override
  public List<StockOutFinishedProductItemVo> waitingForDelivery(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitingForDelivery(search);
  }

  /**
   * 待出库分页
   */
  @Override
  public Page<StockOutFinishedProductItemVo> waitingForDeliveryPage(
    StockOutFinishedProductSearchParamPo search
  ) {
    Page<StockOutFinishedProductItemVo> waitingForDeliveryPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitingForDeliveryPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitingForDeliveryPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitingForDeliveryPage =
      this.baseMapper.waitingForDeliveryPage(
          search.toPage(this.baseMapper.waitingForDeliveryCount(search)),
          search
        );
    List<Long> recordIds = waitingForDeliveryPage
      .getRecords()
      .stream()
      .map(StockOutFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitingForDeliveryPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitingForDeliveryPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitingForDeliveryPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitingForDeliveryPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<?> waitingForDeliveryPageWithChildSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      waitingForDeliveryPage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询待出库最后更新时间
   * @param search 查询条件
   * @return 待出库最后更新时间
   */
  @Override
  public Date waitingForDeliveryLastUpdateTime(
    StockOutFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.waitingForDeliveryLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<StockOutFinishedProductItemVo> done(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.done(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<StockOutFinishedProductItemVo> donePage(
    StockOutFinishedProductSearchParamPo search
  ) {
    Page<StockOutFinishedProductItemVo> donePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return donePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return donePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    donePage =
      this.baseMapper.donePage(
          search.toPage(this.baseMapper.doneCount(search)),
          search
        );
    List<Long> recordIds = donePage
      .getRecords()
      .stream()
      .map(StockOutFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return donePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return donePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    donePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return donePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<?> donePageWithChildSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      donePage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date doneLastUpdateTime(StockOutFinishedProductSearchParamPo search) {
    return this.baseMapper.doneLastUpdateTime(search);
  }

  /**
   * 已撤销
   */
  @Override
  public List<StockOutFinishedProductItemVo> undone(
    StockOutFinishedProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.undone(search);
  }

  /**
   * 已撤销分页
   */
  @Override
  public Page<StockOutFinishedProductItemVo> undonePage(
    StockOutFinishedProductSearchParamPo search
  ) {
    Page<StockOutFinishedProductItemVo> undonePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return undonePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return undonePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    undonePage =
      this.baseMapper.undonePage(
          search.toPage(this.baseMapper.undoneCount(search)),
          search
        );
    List<Long> recordIds = undonePage
      .getRecords()
      .stream()
      .map(StockOutFinishedProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return undonePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return undonePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    undonePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return undonePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 成品出库单分页查询结果
   */
  @Override
  public Page<?> undonePageWithChildSearch(
    StockOutFinishedProductSearchParamPo search
  ) {
    return appendWithChild(
      undonePage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询已撤销最后更新时间
   * @param search 查询条件
   * @return 已撤销最后更新时间
   */
  @Override
  public Date undoneLastUpdateTime(
    StockOutFinishedProductSearchParamPo search
  ) {
    return this.baseMapper.undoneLastUpdateTime(search);
  }
}
